import { Component, Input, OnInit, Inject, forwardRef, ViewChild, ElementRef } from '@angular/core';

import { IonSegment } from '@ionic/angular';

import { ComItem } from '../../route/entry/com-item';
import { EventService } from '../../shared/service/event.service';
import { HttpService } from '../../shared/service/http.service';
import { AppGlobalService } from '../../shared/service/app-global.service';
@Component({
  selector: 'app-button-nav-four',
  templateUrl: './button-nav-four.component.html',
  styleUrls: ['./button-nav-four.component.scss'],
})
export class ButtonNavFourComponent implements OnInit {

  @ViewChild("segment", { read: ElementRef }) private segment: ElementRef;
  @ViewChild('segment', null) ionSegment: IonSegment;
  receiverTag = 'ButtonNavFourComponentReceiver';
  subComs4: ComItem[];
  @Input() tagData: any;
  aWidth: string;
  isSelected: boolean;
  currentClickObj: any;
  currentCLickIndexTab: any;
  isRootURL: any; // 用于检查URL是否有变化
  selectedSegment = 0;
  isAutoFillData: undefined;
  constructor(
    private eventService: EventService,
    private httpService: HttpService,
    private appGlobalService: AppGlobalService
  ) {
    if (this.eventService.eventEmit.listenerCount(this.receiverTag) > 0) {
      this.eventService.eventEmit.removeListener(this.receiverTag);
    }
    this.eventService.eventEmit.on(this.receiverTag, res => {
      if (localStorage.getItem(this.receiverTag + 'Tag')) {
        localStorage.removeItem(this.receiverTag + 'Tag');
        this.subComs4 = res.coms;
      }
    });
  }

  async segmentChanged(e: any) {
    try {
      const index = e.detail.value;
      const segmentButton = this.segment.nativeElement.children[index];
      segmentButton.scrollIntoView({
        behavior: 'smooth',
        inline: 'center',
        block: 'nearest'
      });
      await this.showIndicator();
      if (this.tagData.data) {
        this.httpService.post('application/part',
          {
            viewId: this.tagData.data[index].partLink.target,
            sessionId: localStorage.getItem("sessionId"),
            params: this.tagData.data[index].partLink.params
          }, (res: any) => {
            if (res) {
              const tmpData = JSON.parse(res.script);
              if (this.isAutoFillData && this.isAutoFillData === true) {
                tmpData.tags[0].isAutoFillData = true;
              }
              // 发送事件
              const eventEmitObj = { data: tmpData, receiverTag: this.receiverTag };
              localStorage.setItem('generatedComItemWithBufferTag', JSON.stringify(eventEmitObj));
              this.eventService.eventEmit.emit('generatedComItemWithBuffer', '');
            }
          });
      }
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }

  showIndicator() {
    const len = this.tagData.data.length;
    // for (let i = 0; i < len; i++) {
    //     document.getElementById('segmentIndicator' + i).style.display = "none";
    // }

    // bug: #574 切换tab页后应从当前tab的第一条信息开始展示
    const contents = document.querySelectorAll('ion-content');
    const ele = document.querySelector('ion-content #scrollContent');
    let target = null;
    contents.forEach(item => {
      if (this.isChildOf(ele, item)) {
        target = item;
      }
    });
    target.getScrollElement().then(e => {
      if (e.scrollTop >= document.getElementById('scrollContent').offsetTop) {
        target.scrollToPoint(0, document.getElementById('scrollContent').offsetTop + 44);
      }
    });
  }
  /**
   * 判断是否子节点
   * @param child 子节点
   * @param parent 父节点
   */
  isChildOf(child, parent) {
    let parentNode;
    if (child && parent) {
      parentNode = child.parentNode;
      while (parentNode) {
        if (parent === parentNode) {
          return true;
        }
        parentNode = parentNode.parentNode;
      }
    }
    return false;
  }
  async ngOnInit() {
    try {
      this.isAutoFillData = undefined;
      const that = this;
      this.aWidth = 100 / this.tagData.data.length + '%';
      const cDataObj = this.tagData.currentData;
      this.selectedSegment = +this.tagData.currentTab;
      if (cDataObj !== undefined) {
        const tags = cDataObj.tags;
        if (tags !== undefined && tags.length > 0) {
          that.httpService.post('application/part',
            {
              viewId: this.tagData.data[0].partLink.target,
              sessionId: localStorage.getItem("sessionId"),
              params: this.tagData.data[0].partLink.params
            }, (res: any) => {
              if (res) {
                const tmpData = JSON.parse(res.script);
                if (cDataObj.tags[0] && cDataObj.tags[0].isAutoFillData !== undefined) {
                  tmpData.tags[0].isAutoFillData = cDataObj.tags[0].isAutoFillData;
                  this.isAutoFillData = cDataObj.tags[0].isAutoFillData;
                }
                // #task-view-916
                if (this.tagData.refresh) {
                  tmpData.isPullToRefresh = this.tagData.refresh;
                }
                // tmpData.isPullToRefresh = true;
                // 发送事件
                const eventEmitObj = { data: tmpData, receiverTag: this.receiverTag };
                localStorage.setItem('generatedComItemWithBufferTag', JSON.stringify(eventEmitObj));
                this.eventService.eventEmit.emit('generatedComItemWithBuffer', '');
              }
            });
        }
      }
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }


  get(obj) {
    const params = {
      pageId: obj.target,
      params: obj.params,
      sessionId: localStorage.getItem('sessionId')
    };
    this.appGlobalService.goToForward(params);
  }

}
